<template>
  <view class="cart">
    <!-- <tn-navbar
      z-index="1"
      index-url="/pages/index"
      fixed
      :bottom-shadow="false"
      :is-back="false"
      height="80rpx"
      >购物车</tn-navbar
    > -->

    <view class="cart-container">
      <scroll-view scroll-y scroll-with-animation :scroll-top="leftScrollViewTop"
        :style="{ height: scrollViewHeight + 'px' }">
        <tn-checkbox-group v-model="basicCheckbox" @change="handleCheck" size="xl" active-color="tn-bg-main">
          <tn-swipe-action class="swipe-action">
            <tn-swipe-action-item v-for="(item, index) in cartList" :key="item.id" :options="defaultSwipeData">
              <tn-list class="cart-list">
                <view class="cart-item tn-flex-row">
                  <view class="cart-item-checkbox tn-flex-1">
                    <tn-checkbox class="cart-checkbox" :name="item.id"></tn-checkbox>
                  </view>
                  <view class="cart-item-content tn-flex-9 tn-flex-row">
                    <view class="cart-item-content-img tn-flex-1">
                      <img :src="item.goodsImgs[0]" />
                    </view>

                    <view class="cart-item-content-info tn-flex-3 tn-flex-column">
                      <view class="goods-name">{{ item.goodsName }}</view>
                      <view class="price-num tn-flex-row">
                        <view class="goods-price tn-flex-2">￥{{ item.goodsPrice }}</view>
                        <view class="goods-num tn-flex-1">
                          <tn-number-box v-model="item.num" :min="1" bg-color="tn-bg-main"
                            @change="handleUpdateNum(item.id, $event)"></tn-number-box>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </tn-list>
            </tn-swipe-action-item>
          </tn-swipe-action>
        </tn-checkbox-group>
      </scroll-view>
    </view>
    <view class="cart-tools tn-flex-row">
      <view class="tn-flex-2">
        <tn-checkbox-group v-model="allCheckbox" size="xl" @change="handleAllCheck" active-color="tn-bg-main">
          <tn-checkbox name="all" class="cart-all-checkbox">全选</tn-checkbox>
        </tn-checkbox-group>
      </view>

      <view class="price-total tn-flex-5">
        合计：￥{{ totalPrice }}
      </view>
      <view class="settlement-btn tn-flex-2 tn-bg-main">去结算</view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import TnNavbar from "@/tuniao-ui/components/tn-navbar/src/Navbar.vue";
import TnCheckbox from "@/tuniao-ui/components/tn-checkbox/src/Checkbox.vue";
import TnCheckboxGroup from "@/tuniao-ui/components/tn-checkbox/src/CheckboxGroup.vue";
import TnSwipeAction from "@/tuniao-ui/components/tn-swipe-action/src/SwipeAction.vue";
import TnSwipeActionItem from "@/tuniao-ui/components/tn-swipe-action/src/SwipeActionItem.vue";
import TnNumberBox from "@/tuniao-ui/components/tn-number-box/src/NumberBox.vue";
import { CheckboxGroupModelValue, SwipeOptionData } from "@/tuniao-ui/types";
import TnList from "@/tuniao-ui/components/tn-list/src/List.vue";
import { findCart, updateNum } from "@/api/order";
import { navPage } from "@/tuniao-ui/utils";
import { useUserStore } from "@/tuniao-ui/store/user";
import { navLogin, navBack } from "@/tuniao-ui/utils";
import { loading, closeLoading } from "@/tuniao-ui/utils/messageUtils";
import { ResultEnum } from "@/enums/httpEnum";
import { Cart } from "./lib/Cart";

const userStore = useUserStore();
const isLogin = ref<boolean>(false);

const scrollViewHeight = ref(0); // scroll-view的高度
const leftScrollViewTop = ref(0); // scroll-view的的滚动高度, 更改这个值可以设定滚动到某个区域

const basicCheckbox = ref<number[]>([]);
const allCheckbox = ref<string[]>([]);

const totalPrice = ref<number>(0);


// 选项数据
const defaultSwipeData: SwipeOptionData[] = [
  { text: "删除", icon: "delete", bgColor: "#E83A30" },
];

const cartList = ref<Cart[]>([]);

const handleUpdateNum = (id: number, num: number) => {
  loading({ title: "加载中" });
  updateNum({ id: id, num: num }).then((res) => {

    // 更新价格
    updateTotal();
    closeLoading();
  });
}

const handleCheck = (value: CheckboxGroupModelValue) => {

  // 如果选中的长度和购物车长度一样 就是全选了
  if (cartList.value.length === value.length) {
    // 全选选中
    allCheckbox.value.push("all");
  } else {
    allCheckbox.value = [];
  }
  
 
  // 更新价格
  updateTotal();

}

// 全选事件
const handleAllCheck =  (value: CheckboxGroupModelValue) => {
  console.log(value, "触发全选事件");
  basicCheckbox.value = [];
  // 如果有值就是全选
  if (value.length > 0) {
    cartList.value.forEach(cart => {
      basicCheckbox.value.push(cart.id);
    })
  }
  updateTotal();
}

const updateTotal = () => {

  // 当前选中项
  let carts:Cart[] = [];
  // 遍历选中ids 
  basicCheckbox.value.forEach(checkValue => {
    // 把对应数据过滤出来
    let cartsTemp = cartList.value.filter(item => {
      return item.id === checkValue;
    })
    carts = carts.concat(cartsTemp);
  })
 

  // 清零
  totalPrice.value = 0;
  carts.forEach(cart => {
    // 计算总价
    totalPrice.value += cart.goodsPrice * cart.num; 
  })
}


onMounted(async () => {
  // 获取当前系统信息
  const systemInfo = uni.getSystemInfoSync();
  const { safeArea, windowWidth, windowHeight } = systemInfo;
  const bottomRpx = (200 / 750) * windowWidth; // 底部tabbar的高度，200rpx换算成px，这个是rpx与px的换算公式
  //const topRpx = (80 / 750) * windowWidth; // 分类列表顶部搜索的高度，80rpx换算成px 比分类页低40rpx就少减一些
  const topRpx = 0;
  const wHeight = safeArea?.height; // 安全区域高度，有的机型底部有横条，这个是增加的高度
  // 没有就用屏幕高度
  if (wHeight) {
    scrollViewHeight.value = wHeight - bottomRpx - topRpx;
  } else {
    scrollViewHeight.value = windowHeight - bottomRpx - topRpx;
  }


  isLogin.value = userStore.isLogin();
  if (isLogin.value) {

    findCart().then((res) => {
      //console.log(res);
      if (res.code === ResultEnum.SUCCESS) {
        cartList.value = cartList.value.concat(res.result);
        //console.log(cartList.value);
      }
    })

  }
});
</script>

<style lang="scss" scoped>
img {
  width: 100%;
  height: 100%;
}

.swipe-action {
  width: 100%;
}

.cart {


  // list是tnlist组件
  &-list {
    margin-bottom: 10rpx;
    width: 100%;
  }

  &-item {
    height: 150rpx;
    align-items: center;


    &-checkbox {
      height: 50rpx;
    }

    &-content {
      height: 100%;

      &-img {
        width: 150rpx;
        height: 150rpx;
        border-radius: 10rpx;
        overflow: hidden;
      }

      &-info {
        width: 70%;
        margin-left: 20rpx;
        display: flex;
        align-items: center;

        .price-num {
          .goods-price {
            color: #f00;
            font-size: 35rpx;
          }
        }

        view {
          width: 100%;
          height: 50%;
          align-items: center;
        }
      }
    }
  }

  &-tools {
    padding: 0 25rpx;
    border-top: 1px solid #efefef;
    background-color: #fff;
    height: 100rpx;
    width: 100%;
    display: flex;
    align-items: center;

    .cart-all-checkbox {
      font-size: 28rpx;
    }

    .settlement-btn {
      height: 70%;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50rpx;
    }
  }
}
</style>
